package netty.socket.sticky_unpack.LengthFieldBasedFrameDecoder;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author: 程序员七哥
 * @date: 2021-12-05
 * @description: 自定义客户端消息处理器
 */
public class ClientSocketHandler extends SimpleChannelInboundHandler<String> {

    /** 模板方法，想比 ChannelInboundHandlerAdapter 多了将消息资源释放的逻辑 */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        System.out.println(channelHandlerContext.channel().remoteAddress() + ":" + msg);
        // 发送消息给服务端
        channelHandlerContext.channel().writeAndFlush("from client:" + LocalDateTime.now());
        TimeUnit.MILLISECONDS.sleep(500);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().writeAndFlush("from client: talk is begin!");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
